
/**
 * RosterActivity.java
 * @author Jason Lu
 * @date 2013-9-24
 * @version 1.0
 */
package com.x52im.mall.logic.shop;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.eva.android.widget.AListAdapter2;
import com.eva.android.widget.DataLoadingAsyncTask;
import com.eva.framework.dto.DataFromClient;
import com.eva.framework.dto.DataFromServer;
import com.eva.framework.dto.SysActionConst;
import com.x52im.mall.CommonPaymentActivity;
import com.x52im.mall.IntentFactory;
import com.x52im.mall.ObjectFactory;
import com.x52im.mall.PayPalConfig;
import com.x52im.mall.dto.CommonProcessorConst;
import com.x52im.mall.shop.dto.JobDispatchConst;
import com.x52im.mall.shop.dto.SO;
import com.x52im.mall.shop.dto.SODetail;
import com.x52im.rbchat.R;
import com.x52im.mall.MallGlobal;
import com.eva.android.widget.DataLoadableActivity;
import com.paypal.android.sdk.payments.PayPalService;

/**
 * @author Jason
 * 
 */
public class OrderManageActivity extends DataLoadableActivity
{
	/** 列表 */
	private ListView orderListView;
	/** 列表Adapter */
	private MessagesListAdapter orderListAdapter;
	
	private View backBtn = null;
	private Button shopCar = null;
	private TextView shopCarCountView = null;

	private ViewGroup layoutForNoOrders = null;
	
	private static SO itemSO;
	private static int shopCarCount = 0;

	@Override
	protected void initViews(Bundle savedInstanceState)
	{
		// 养成良好习惯：首先设置主layout，确保后绪的操作中使用到的组件都可以被find到
		setContentView(R.layout.common_mall_shop_layout_order_manage);
		//对自定义标题栏中的组件进行设定
//		this.getCustomeTitleBar().getRightGeneralButton().setVisibility(View.VISIBLE);
//		this.getCustomeTitleBar().getRightGeneralButton().setText("");
//		this.getCustomeTitleBar().getRightGeneralButton().setBackgroundResource(R.drawable.common_mall_shop_shopping_btn);

		// 列表及列表的adapter
		orderListView = (ListView) findViewById(R.id.common_mall_shop_layout_order_manage_good_listView);
		orderListAdapter = new MessagesListAdapter(this);
		orderListView.setAdapter(orderListAdapter);
		
		shopCar = (Button)findViewById(R.id.common_mall_shop_layout_order_manage_good_shopcar);
		shopCarCountView = (TextView)findViewById(R.id.common_mall_shop_layout_order_manage_good_shopcar_count);
		backBtn = findViewById(R.id.common_mall_shop_layout_order_manage_good_backBtn);
		layoutForNoOrders = findViewById(R.id.common_mall_shop_layout_order_manage_good_listView_noOrdersLL);

//		this.setTitle(R.string.common_mall_shop_order_manage_title);
		
		startService(PayPalConfig.getPayPalServiceIntent(OrderManageActivity.this));
	}

	/**
	 * 为各UI功能组件增加事件临听的实现方法. {@inheritDoc}
	 */
	@Override
	protected void initListeners()
	{
		shopCar.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v)
			{
				startActivity(IntentFactory.createShopCarActivityIntent(OrderManageActivity.this));
			}
		});
		
		backBtn.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		
		
		
//		orderListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
//		{
//
//			@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
//			{
//				// TODO Auto-generated method stub
//				itemSO = orderListAdapter.getListData().get(current_position);
//				startActivity(IntentFactory.createOrderComfirmDetailActivityIntent(OrderManageActivity.this, itemSO));
//			}
//		});
	}

	/**
	 * 本方法被loadData调用，本类里用于查询列表中各产品的库存数据.
	 * 
	 * @param params
	 *            loadData中传进来的参数，本类中该参数没有被用到
	 */
	@Override
	protected DataFromServer queryData(String... params)
	{
//		return RobotimeMall.getMallProviderInstance(this).getRobotimeMall().getAuthedService().sendObjToServer(
//				DataFromClient.n().setProcessorId(CommonProcessorConst.PROCESSOR_SHOP_NEED$AUTHED)
//				.setJobDispatchId(JobDispatchConst.SHOP_GOODS_MGR_NEED$AUTHED)
//				.setActionId(SysActionConst.ACTION_APPEND2)
//				.setNewData(RobotimeMall.getMallProviderInstance(this).getRobotimeMall().getLoginedUserUid()));
		return null;
	}

	/**
	 * 本方法的目的是把loadData里查询出来的产品库存按产品编号所对应的列表行更新上去并于以刷新显示.
	 */
	// 本类中的loadData并不用像通常的用专用影一样：刷新整个界面数据，本类中
	// 权用于点击“刷新库存”时刷新列表明细中的各库存，权此而已。也就是说，本
	// 类中的loadData实现的是刷新列表中的库存数量，一定要注意
	@Override
	protected void refreshToView(Object dataToView)
	{
//		@SuppressWarnings("unchecked")
//		ArrayList<SO> listData = (ArrayList<SO>) dataToView;
//
//		orderListAdapter.setListData(listData);
//		// 更新Ui
//		orderListAdapter.notifyDataSetChanged();
	}

//	// 去掉EVA通用类中的默认“返回”菜单项
//	public boolean onCreateOptionsMenu(Menu menu)
//	{
//		return false;
//	}
	
	
	protected void onResume()
	{
		shopCarCount = MallGlobal.getMallProviderInstance(this).getRobotimeMall().getShopCarProvider().getGoodsCount();
		if(shopCarCount == 0)
			shopCarCountView.setVisibility(View.GONE);
		else
		{
			shopCarCountView.setVisibility(View.VISIBLE);
			shopCarCountView.setText(shopCarCount + "");
		}
		new DataAsyncTask().execute();
		super.onResume();
	}
	
	@Override
	public void onDestroy()
	{
		stopService(new Intent(this, PayPalService.class));
		super.onDestroy();
	}

	// ------------------------------------------------------------------------------------------------------------
	/**
	 * 自定义明细列表的adapter类实现.
	 */
	private class MessagesListAdapter extends AListAdapter2<SO>
	{
		/** 记录选中的ListView的行索引值以备后用（目前是在：单击、长按2类事件中保存了此索引值）. */
		protected int selectedListViewIndex = -1;

		public MessagesListAdapter(Activity context)
		{
			super(context, R.layout.common_mall_shop_layout_order_manage_good_list_item);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			TextView viewOrderId = null;
			TextView viewOrderDate = null;
			TextView viewNo = null;
			TextView viewCurrency = null;
			TextView viewPrice = null;
			TextView viewStatus = null;
			Button payBtn = null;
			Button commentBtn = null;

			// ----------------------------------------------------------------------------------------
			// （1）UI初始化
			// 当的item布局实例已经存在（不在存，意味着这个item刚好从不可见区移到可见区时）
			// ** 根据android的列表ui实现，为了节比资源占用，假如列表有100行而可见区显示5行，那么任何时候
			// ** 这个列表中只会有5个item的UI存在，其它的item都是当被转到可见区时自动把自
			// ** 已的数据实时地更新列UI上，以便查看，也就是说item的UI并不是与后台数据一
			// ** 一对应的，所以正如API文档里说的，convertView并不能确保它总能按你的想法保持不为null
			boolean needCreateItem = (convertView == null);
			// 正在操作的列表行的数据集
			final SO rowData = listData.get(position);
			if (needCreateItem)
				// 明细item的UI实例化
				convertView = layoutInflater.inflate(itemResId, null);
			// item里的操作组件实例
			viewNo = (TextView) convertView.findViewById(R.id.common_mall_shop_layout_order_manage_good_item_order_no);
			viewOrderId = (TextView) convertView.findViewById(R.id.common_mall_shop_layout_order_manage_good_item_order_id);
			viewOrderDate = (TextView) convertView.findViewById(R.id.common_mall_shop_layout_order_manage_good_item_order_date);
			viewCurrency = (TextView) convertView.findViewById(R.id.common_mall_shop_layout_order_manage_good_item_goodPriceCurrency);
			viewPrice = (TextView) convertView.findViewById(R.id.common_mall_shop_layout_order_manage_good_item_goodPrice);
			viewStatus = (TextView) convertView.findViewById(R.id.common_mall_shop_layout_order_manage_good_item_status);
			payBtn = (Button) convertView.findViewById(R.id.common_mall_shop_layout_order_manage_good_item_goPayBtn);
			commentBtn = (Button)convertView.findViewById(R.id.common_mall_shop_layout_order_manage_good_item_goCommentBtn);

			// ----------------------------------------------------------------------------------------
			// （2）增加事件处理器
			// 各操作组件的事件监听器只需要在convertView被实例化时才需要重建（convertView需要被实例化
			// 当然就意味着它上面的所有操作组件都已经重新新建了）
			// ** 关于事件处理器的说明：事件处理器的增加其实可以不这么麻烦，直接每getView一次就给组件new一个处理器，
			// ** 这样做的好处是简单，但显然存在资源浪费（每刷新一次view就新建监听器）。而现在的实现就跟Android的列表
			// ** 实现原理一样，在切换到下一组item前，监听器永远只有一屏item的数量（刷新时只需要即时刷新对应item的数据到
			// ** 它的监听器里），这样就节省了资源开销！
			PayOnClickListener payListener = new PayOnClickListener();
			CommentOnClickListener commnetListener = new CommentOnClickListener();
			if (needCreateItem)
			{
				//*** 
				payBtn.setOnClickListener(payListener);
				payBtn.setTag(payListener);
				
				commentBtn.setOnClickListener(commnetListener);
				commentBtn.setTag(commnetListener);
			}

			// ----------------------------------------------------------------------------------------
			// （3）
			// 给标签设置值，以供用户查看
			viewNo.setText(position + 1 + ".");
			viewOrderId.setText(rowData.getOrder_id());
			viewOrderDate.setText(rowData.getCreate_time());
			viewCurrency.setText(rowData.getOrder_currency().equals("0") ? "$" : "￥");
			viewPrice.setText(rowData.getOrder_total());
			if ("0".equals(rowData.getOrder_status()))
			{
				payBtn.setVisibility(View.VISIBLE);
				// 点击整体item layout也能响应事件，提高用户体验哦（因为pay的按钮太小了！）
//				convertView.setOnClickListener(payListener);
			}
			else
			{
				payBtn.setVisibility(View.GONE);
			}
			
			if("3".equals(rowData.getOrder_status()) && !isAllEvaluated(rowData))
			{
				commentBtn.setVisibility(View.VISIBLE);
//				convertView.setOnClickListener(commnetListener);
			}
			else
			{
				commentBtn.setVisibility(View.GONE);
			}
			viewStatus.setText(String.valueOf(ObjectFactory.createSOStatusRenderer(OrderManageActivity.this).getNameById(rowData.getOrder_status())));
			
			//** 确保每次item被刷新时都更新操作组件事件监听器中要记录的该item所对应的 列表的行索引号
			//** 这样就能很好地确保行索引号的正确性了
//			EditQuantityTextWatcher editListener = (EditQuantityTextWatcher) viewQuantity.getTag();
//			editListener.setPosition(position);
			payListener = (PayOnClickListener) payBtn.getTag();
			payListener.setPosition(position);
			
			commnetListener = (CommentOnClickListener)commentBtn.getTag();
			commnetListener.setPosition(position);
			
			return convertView;
		}

		@Override
		public void notifyDataSetChanged()
		{
			super.notifyDataSetChanged();

			//
			if(this.getCount() <= 0)
			{
				layoutForNoOrders.setVisibility(View.VISIBLE);
				orderListView.setVisibility(View.GONE);
			}
			else
			{
				layoutForNoOrders.setVisibility(View.GONE);
				orderListView.setVisibility(View.VISIBLE);
			}
		}

		@SuppressWarnings("unused")
		public int getSelectedListViewIndex()
		{
			return selectedListViewIndex;
		}

		@SuppressWarnings("unused")
		public void setSelectedListViewIndex(int selectedListViewIndex)
		{
			this.selectedListViewIndex = selectedListViewIndex;
			// this.notifyDataSetChanged();
		}
		
		/**
		 * 支付按钮事件监听器.
		 */
		private class PayOnClickListener implements View.OnClickListener
		{
			int position = 0;

			public void setPosition(int position)
			{
				this.position = position;
			}

			@Override
			public void onClick(View v)
			{
				itemSO = listData.get(position);
				startActivityForResult(IntentFactory.createPaymentActivityIntent(OrderManageActivity.this, itemSO, null,  CommonPaymentActivity.PAYPAL_PAYMENT_DEVICE), 0);
			}
		}
		
		private class CommentOnClickListener implements View.OnClickListener
		{
			int position = 0;

			public void setPosition(int position)
			{
				this.position = position;
			}

			@Override
			public void onClick(View v)
			{
				itemSO = getItem(position);
				startActivity(IntentFactory.createOrderComfirmDetailActivityIntent(OrderManageActivity.this, itemSO));
			}
		}
		
		private boolean isAllEvaluated(SO so)
		{
			for(SODetail sd : so.getSoDetails())
			{
				if(!sd.isEvaludated())
				{
					return false;
				}
			}
			return true;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode == Activity.RESULT_OK)
			Toast.makeText(OrderManageActivity.this, R.string.common_mall_shop_order_confirm_result_pay_success, Toast.LENGTH_LONG).show();
		else
			Toast.makeText(OrderManageActivity.this, R.string.common_mall_shop_order_confirm_result_pay_faliure, Toast.LENGTH_LONG).show();
	}
	
	/**
	 * 提交数据请求和处理的异步执行线程实现类.
	 */
	protected class DataAsyncTask extends DataLoadingAsyncTask<String, Integer, DataFromServer>
	{
		public DataAsyncTask()
		{
			super(OrderManageActivity.this, $$(R.string.common_mall_main_entrance_loading_data));
		}

		/**
		 * 
		 * @param params 外界传进来的参数
		 * @return 查询结果，将传递给onPostExecute(..)方法
		 */
		@Override
		protected DataFromServer doInBackground(String... params)
		{
			return MallGlobal.getMallProviderInstance(OrderManageActivity.this).getRobotimeMall().getAuthedService().sendObjToServer(
					DataFromClient.n().setProcessorId(CommonProcessorConst.PROCESSOR_SHOP_NEED$AUTHED)
					.setJobDispatchId(JobDispatchConst.SHOP_GOODS_MGR_NEED$AUTHED)
					.setActionId(SysActionConst.ACTION_APPEND2)
					.setNewData(MallGlobal.getMallProviderInstance(OrderManageActivity.this).getRobotimeMall().getLoginedUserUid()));
		}

		/**
		 * 处理服务端返回的登陆结果信息.
		 */
		protected void onPostExecuteImpl(Object result)
		{
			@SuppressWarnings("unchecked")
			ArrayList<SO> data = (ArrayList<SO>) result;
			
			orderListAdapter.setListData(data);
			// 更新Ui
			orderListAdapter.notifyDataSetChanged();
		}
	}
	
}
